'use client'

import { createContext, useContext, useState, useEffect, ReactNode } from 'react'
import { authAPI } from '@/lib/api'
import { clearUserCache, setTabToken, getTabToken, clearTabToken, hasValidTabToken, getAllActiveTokens, hasValidTabTokenEnhanced, persistTabToken } from '@/lib/cache'
import { safeSetState } from '@/lib/utils/safeStateUpdate'

interface User {
  id: string
  username: string
  email: string
  role: 'ADMIN' | 'EDITOR' | 'VIEWER'
  avatar?: string
  status: string
}

interface AuthContextType {
  user: User | null
  isAuthenticated: boolean
  isLoading: boolean
  login: (username: string, password: string) => Promise<void>
  register: (username: string, email: string, password: string, role?: string) => Promise<void>
  logout: () => Promise<void>
  refreshUser: () => Promise<void>
}

const AuthContext = createContext<AuthContextType | undefined>(undefined)

export function AuthProvider({ children }: { children: ReactNode }) {
  const [user, setUser] = useState<User | null>(null)
  const [isLoading, setIsLoading] = useState(true)
  const [isClient, setIsClient] = useState(false)

  // 确保在客户端运行
  useEffect(() => {
    setIsClient(true)
  }, [])

  // 检查本地存储的token
  useEffect(() => {
    if (!isClient) return
    
    // 使用 setTimeout 来避免在渲染过程中调用 setState
    const checkToken = () => {
      // 使用新的标签页隔离token系统，检查是否有有效的token
      if (hasValidTabTokenEnhanced()) {
        console.log('🔍 检测到有效token，尝试恢复用户状态')
        // 只有在有有效token时才尝试刷新用户信息
        refreshUser()
      } else {
        // 如果没有token，尝试从localStorage恢复
        console.log('🔍 未检测到有效token，尝试恢复其他标签页的token')
        const allTokens = getAllActiveTokens()
        if (allTokens.length > 0) {
          console.log('🔄 尝试恢复其他标签页的token')
          // 自动恢复最活跃的token
          const mostActive = allTokens[0]
          setTabToken(mostActive.token)
          // 再次检查token有效性
          if (hasValidTabTokenEnhanced()) {
            console.log('✅ 成功恢复token，开始刷新用户信息')
            refreshUser()
          } else {
            console.log('❌ 恢复的token无效，设置为未认证状态')
            setIsLoading(false)
          }
        } else {
          console.log('🔍 未检测到有效token，设置为未认证状态')
          setIsLoading(false)
        }
      }
    }
    
    // 延迟执行以避免在渲染过程中调用 setState
    setTimeout(checkToken, 0)
  }, [isClient])

  // 刷新用户信息
  const refreshUser = async () => {
    try {
      // 再次检查token是否有效
      if (!hasValidTabTokenEnhanced()) {
        console.log('🔍 Token无效，跳过用户信息刷新')
        safeSetState(setUser, null)
        safeSetState(setIsLoading, false)
        return
      }
      
      console.log('🔄 开始刷新用户信息...')
      const userData = await authAPI.getCurrentUser()
      safeSetState(setUser, userData)
      safeSetState(setIsLoading, false)
      console.log('✅ 用户信息刷新成功')
    } catch (error) {
      console.error('❌ 刷新用户信息失败:', error)
      // token可能已过期或无效，清除当前标签页的token
      if (isClient) {
        clearTabToken()
      }
      safeSetState(setUser, null)
      safeSetState(setIsLoading, false)
    }
  }

  // 登录
  const login = async (username: string, password: string) => {
    try {
      setIsLoading(true)
      const response = await authAPI.login({ username, password })
      
      // 保存token到本地存储
      if (isClient) {
        setTabToken(response.token)
        // 持久化token
        persistTabToken()
        console.log('🔐 Token已保存到标签页并持久化')
      }
      
      // 设置用户信息
      setUser(response.user)
      console.log('👤 用户信息已设置:', response.user.username)
    } catch (error) {
      console.error('❌ 登录失败:', error)
      throw error
    } finally {
      setIsLoading(false)
    }
  }

  // 注册
  const register = async (username: string, email: string, password: string, role: 'ADMIN' | 'EDITOR' | 'VIEWER' = 'VIEWER') => {
    try {
      setIsLoading(true)
      const response = await authAPI.register({ username, email, password, role })
      
      // 保存token到本地存储
      if (isClient) {
        setTabToken(response.token)
      }
      
      // 设置用户信息
      setUser(response.user)
    } catch (error) {
      console.error('Registration failed:', error)
      throw error
    } finally {
      setIsLoading(false)
    }
  }

  // 登出
  const logout = async () => {
    try {
      await authAPI.logout()
    } catch (error) {
      console.error('Logout failed:', error)
    } finally {
      // 清除本地存储和用户状态
      if (isClient) {
        // 清理当前标签页的token
        clearTabToken()
        // 清理其他用户相关缓存
        clearUserCache()
      }
      setUser(null)
    }
  }

  const value: AuthContextType = {
    user,
    isAuthenticated: !!user,
    isLoading,
    login,
    register,
    logout,
    refreshUser,
  }

  return (
    <AuthContext.Provider value={value}>
      {children}
    </AuthContext.Provider>
  )
}

export function useAuth() {
  const context = useContext(AuthContext)
  if (context === undefined) {
    throw new Error('useAuth must be used within an AuthProvider')
  }
  return context
}
